﻿using iTextSharp.text.pdf;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Word = Microsoft.Office.Interop.Word;
using Aspose.Words;
namespace CTOOLS
{
    public class WordFileH
    {
        object missing = System.Reflection.Missing.Value;
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public bool WordSplitPdf(ref Word.Document wDoc,string fileName, string savePath,int officeV)
        {
            bool breturn = false;
            string[] sArray = fileName.Split(new char[1] { '.' });
            if (sArray.Length > 0)
            {
                try
                {
                    savePath=savePath + "\\" + sArray[0];
                    if (CreateDirectory(savePath) == true)
                    {//创建案号文件夹
                        List<string> listSFName = new List<string>();
                        GetWordSections(wDoc, ref listSFName);
                        if (listSFName.Count == wDoc.Sections.Count)
                        {
                            ArrayList spNum = new ArrayList();
                            int p_begin = 1;//起始页码
                            int p_end = 0;//结束页码
                            string sFName = "";
                            if (!string.IsNullOrEmpty(sArray[0])) savePath = savePath + "\\";
                            string Apdf = savePath + fileName.Substring(0, fileName.Length - sArray[sArray.Length - 1].Length) + ".PDF";
                            if (officeV >= 2013)
                            {
                                if (ConvertOfficeToPdf(ref wDoc, Apdf) == false)
                                {
                                    breturn = false;
                                    return breturn;
                                }
                            }
                            else
                            {
                                if (AsposeWordToPdf(ref wDoc, Apdf, savePath) == false)
                                {
                                    breturn = false;
                                    return breturn;
                                }
                            }
                            

                            wDoc.Activate();
                            for (int j = 1; j <= wDoc.Sections.Count; j++)
                            {
                                object pn = wDoc.Sections[j].Range.Characters.Last.get_Information(Word.WdInformation.wdActiveEndPageNumber);
                                p_end = System.Convert.ToInt32(pn);
                                sFName = savePath + sArray[0] + "." + listSFName[j-1] + ".pdf";//pdf文件名
                                CutPdf(Apdf, sFName, p_begin, p_end, 1);
                                p_begin = p_end + 1;//设置下一页的起始页码
                            }
                            breturn = true;
                        }
                    }       
                }
                catch (Exception e)
                {
                    log.Error("按分节符拆分转换PDF出错", e);
                }
                finally
                {
                    //清理回收站
                    //GC.Collect();
                }
            }

            return breturn;
        }
        /// <summary>
        /// 按照分节符拆分word为单独word文件
        /// </summary>
        /// <param name="wDoc"></param>
        /// <param name="fileName"></param>
        /// <param name="savePath"></param>
        /// <returns></returns>
        public bool WordSplitSectionToWord(ref Word.Document wDoc,string fileName,string savePath)
        {
            bool breturn = false;
            string[] sArray = fileName.Split(new char[1] { '.' });
            if (sArray.Length > 0)
            {
                try
                {
                    if (CreateDirectory(savePath + "\\" + sArray[0]) == true)
                    {//创建案号文件夹
                        List<string> listSFName = new List<string>();
                        GetWordSections(wDoc, ref listSFName);
                        if (listSFName.Count== wDoc.Sections.Count)
                        {
                            //实例化Document对象 
                            Word.Document newWord;
                            //遍历文档所有section，复制文档每个section并分别保存到新建的文档，同时将拆分的文档保存到指定路径
                            for (int i = 1; i <= wDoc.Sections.Count; i++)
                            {
                                newWord = new Word.Document();
                                wDoc.Sections[i].Range.Copy();            
                                newWord.Content.Paste();
                                newWord.SaveAs2(savePath + "\\" + sArray[0] + "\\" + sArray[0] + "." + listSFName[i - 1] + "." + sArray[sArray.Length - 1],
                                    ref missing, ref missing, ref missing, ref missing,
                                    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                                    ref missing, ref missing, ref missing, ref missing, ref missing);
                                newWord.Close(ref missing, ref missing, ref missing);
                            }
                        }
                        breturn = true;
                    }
                }
                catch (Exception e)
                {
                    log.Error("按分节符拆分word出错", e);
                }
                finally
                {
                 //清理回收站
                 GC.Collect();
                }

            }
            return breturn;

        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="sPath"></param>
        /// <returns></returns>
        private Boolean CreateDirectory(string sPath)
        {
            Boolean ibReturn = false;
            if (!Directory.Exists(sPath))
            {
                DirectoryInfo DI = Directory.CreateDirectory(sPath);
                if (DI != null)
                {
                    ibReturn = true;
                }
            }
            else
            {
                ibReturn = true;
            }
            return ibReturn;
        }

        /// <summary>
        /// 获取分节符对应的页眉名称
        /// </summary>
        /// <param name="wDoc"></param>
        /// <param name="listSFName"></param>
        private void GetWordSections(Word.Document wDoc, ref List<string> listSFName)
        {
            listSFName.Clear();
            string[] sNameA = { "说明书摘要", "摘要附图", "权利要求书", "说明书", "说明书附图" };
            List<string> sLName = sNameA.ToList();
            string sHeaderText = "";
            string sHV = "";
            bool sbool = false;
            if (wDoc.Sections.First.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Exists)  // 判断有页眉
            {

                if (wDoc.Sections.Count > 0)
                {
                    wDoc.Activate();
                    Word.HeaderFooter ftr = wDoc.Sections[1].Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
                    Word.Range ftrRange = ftr.Range;
                    Word.Paragraphs paras = ftrRange.Paragraphs;
                    for (int counter = 1; counter <= paras.Count; counter++)
                    {
                        Word.Paragraph para = paras[counter];
                        sHeaderText = para.Range.Text;
                        if (sHeaderText.IndexOf("2006.") >= 0)
                        {
                            sHV = "Table";
                            break;
                        }
                        else if (sHeaderText.IndexOf("2010.") >= 0)
                        {
                            sHV = "Header";
                            break;
                        }
                    }

                    if (sHV == "Header")
                    {
                        for (int j = 1; j <= wDoc.Sections.Count; j++)
                        {
                            sbool = false;
                            sHeaderText = wDoc.Sections[j].Headers[Word.WdHeaderFooterIndex.wdHeaderFooterFirstPage].Range.Text;
                            sHeaderText = sHeaderText.Replace(" ", "");
                            for(int l = 0; l < sLName.Count; l++)
                            {
                                if (sHeaderText.IndexOf(sLName[l]+"\r") >= 0 || sHeaderText.IndexOf(sLName[l] + "\t") >= 0)
                                {
                                    listSFName.Add(sLName[l]);
                                    sbool = true;
                                    break;
                                }  
                            }
                            if(sbool==false) listSFName.Add("其它"+j.ToString());
                        }
                    }
                    else if (sHV == "Table")
                    {
                        for (int k = 1; k <= wDoc.Sections.Count; k++)
                        {
                            if (wDoc.Sections[k].Range.Tables.Count > 0)
                            {
                                Word.Table nowTable = wDoc.Sections[k].Range.Tables[1];
                                // string ss = nowTable.Range.Text;
                                for (int rowPos = 1; rowPos <= nowTable.Rows.Count; rowPos++)
                                {
                                    sHeaderText = nowTable.Cell(rowPos, 1).Range.Text;
                                    sHeaderText = sHeaderText.Replace(" ", "");

                                    for (int l = 0; l < sLName.Count; l++)
                                    {
                                        if (sHeaderText.IndexOf(sLName[l] + "\r") >= 0 || sHeaderText.IndexOf(sLName[l] + "\t") >= 0)
                                        {
                                            listSFName.Add(sLName[l]);
                                            sbool = true;
                                            break;
                                        }
                                    }
                                    if (sbool == false) listSFName.Add("其它" + k.ToString());
                                }
                            }
                        }

                    }
                }

            }
        }
       
        /// <summary>
        /// 提取或删除指定页面为新文件
        /// </summary>
        /// <param name="inputFileName">原始文件全路径</param>
        /// <param name="newFileName">目标文件全路径</param>
        /// <param name="pageBegin">起始页</param>
        /// <param name="pageEnd">终止页</param>
        /// <param name="flag">标志：1-提取，2-删除</param>
        private void CutPdf(string inputFileName, string newFileName, int pageBegin, int pageEnd, int flag)
        {
            int rotation = 0;
            int pageSize = 0;
            int pi = 0;

            PdfReader pdfReader = new PdfReader(inputFileName);
            //string fileName = inputFileName.Substring(0, inputFileName.Length - 4);
            int totalPages = pdfReader.NumberOfPages;
             
            FileStream fs = new FileStream(newFileName, FileMode.Create);
            iTextSharp.text.Document newDocument = new iTextSharp.text.Document();
            PdfWriter pdfWriter = PdfWriter.GetInstance(newDocument, fs);
            pdfWriter.CloseStream = true;
            newDocument.Open();
            PdfContentByte pdfContentByte = pdfWriter.DirectContent;

            if (flag == 1)
            {
                pi = pageBegin;
                pageSize = pageEnd;
            }
            else if (flag == 2)
            {
                pi = 1;
                pageSize = totalPages;
            }

            for (int i = pi; i <= pageSize; i++)
            {
                if (flag == 2)
                {
                    if (i >= pageBegin && i <= pageEnd) continue;
                }

                newDocument.SetPageSize(pdfReader.GetPageSizeWithRotation(i));
                newDocument.NewPage();
                PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader, i);
                rotation = pdfReader.GetPageRotation(i);
                pdfContentByte.AddTemplate(importedPage, 0, 0);
                if (rotation == 90 || rotation == 270)
                {
                    pdfContentByte.AddTemplate(importedPage, 0, -1f, 1f, 0, 0, pdfReader.GetPageSizeWithRotation(i).Height);
                }
                else
                {
                    pdfContentByte.AddTemplate(importedPage, 1f, 0, 0, 1f, 0, 0);
                }
            }
            fs.Flush();
            newDocument.Close();
            pdfReader.Close();
        }


        /// <summary>
        /// office word 转 PDF
        /// </summary>
        /// <param name="wDoc"></param>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        private bool ConvertOfficeToPdf(ref Word.Document wDoc, string targetPath)
        {
            bool result = false;
            object paramMissing = Type.Missing;
            Word.WdExportFormat exportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;

            try
            {
                bool paramOpenAfterExport = false;
                Word.WdExportOptimizeFor paramExportOptimizeFor =
                        Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
                Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
                int paramStartPage = 0;
                int paramEndPage = 0;
                Word.WdExportItem paramExportItem = Word.WdExportItem.wdExportDocumentWithMarkup;//.wdExportDocumentContent;
                bool paramIncludeDocProps = true;
                bool paramKeepIRM = true;
                Word.WdExportCreateBookmarks paramCreateBookmarks =
                        Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool paramDocStructureTags = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1 = false;
                wDoc.ExportAsFixedFormat(targetPath,
                           exportFormat, paramOpenAfterExport,
                           paramExportOptimizeFor, paramExportRange, paramStartPage,
                           paramEndPage, paramExportItem, paramIncludeDocProps,
                           paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                           paramBitmapMissingFonts, paramUseISO19005_1,
                           ref paramMissing);
                result = true;
                log.Debug(targetPath);
            }
            catch(Exception e){
                result=false;
                log.Error("office转换word到pdf失败", e);
            }
            return result;
        }



        private bool AsposeWordToPdf(ref Word.Document wDoc, string targetPath,string savePath)
        {
            bool result = false;
            try
            {
                string sFile = savePath + "\\" + wDoc.Name;
                System.IO.File.Copy(wDoc.FullName, sFile, true);
                Document doc = new Document(sFile);//= wDoc;
                doc.Save(targetPath, SaveFormat.Pdf);
                System.IO.File.Delete(sFile);
                result = true;
            }
            catch (Exception e)
            {
                result = false;
                log.Error("Aspose转换word到pdf失败", e);
            }
            return result;
        }

    }
}
